package com.mgq.netty.c9;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.FixedLengthFrameDecoder;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;

/**
 * @author MaGuangQi
 * @description: 使用netty提供的FixedLengthFrameDecoder解析器
 * {@link FixedLengthFrameDecoder}
 * 客户端
 * @date 2021-12-06 14:45
 **/
@Slf4j
public class SecondSolutionClient {
    public static void main(String[] args) throws InterruptedException {
        NioEventLoopGroup group = new NioEventLoopGroup();
        ChannelFuture future = new Bootstrap().group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                        nioSocketChannel.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                            @Override
                            //建立连接之后
                            public void channelActive(ChannelHandlerContext ctx) throws Exception {
                                char c = 'a';
                                final int maxLength = 16;
                                // 向服务器发送10个报文
                                for (int i = 0; i < 10; i++) {
                                    ByteBuf buffer = ctx.alloc().buffer(maxLength);
                                    // 定长byte数组，未使用部分会以0进行填充
                                    byte[] bytes = new byte[maxLength];
                                    // 生成长度为0~15的数据
                                    for (int j = 0; j < (int) (Math.random() * (maxLength - 1)); j++) {
                                        bytes[j] = (byte) c;
                                    }
                                    buffer.writeBytes(bytes);
                                    c++;
                                    ctx.channel().writeAndFlush(buffer);
                                }
                                ctx.channel().close();
                            }
                        });
                    }
                })
                .connect(new InetSocketAddress("localhost", 8080));

        future.sync();
        Channel channel = future.channel();
        channel.closeFuture().addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                log.debug("channel已经关闭完成,停止group..............");
                group.shutdownGracefully();
            }
        });
    }
}
